<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          v-show="false"
          label="停车场名称">
          <a-input placeholder="请输入停车场名称" v-decorator="['parkName', {}]"/>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="套餐名称">
          <a-input :disabled="isEdit" placeholder="请输入月租车套餐名称"
                   v-decorator="['packageName', { rules: [{ type: 'string', required: true, message: '请输入月租车套餐名称!' }] }]"/>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="车辆类型">
          <a-select :options="monthCarTypeList" v-decorator="['monthlyTypeId', {initialValue:''}]"
                    @select="monthlyTypeSelect"></a-select>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          v-show="false"
          label="月租车辆类型Id">
          <a-input placeholder="请输入月租车辆类型名称" v-decorator="['monthlyTypeName', {}]"/>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="可绑定车位数">
          <a-input-number :disabled="isEdit" :min="0" :max="2100000" :precision="0" placeholder="请输入可绑定车位数" style="width:165px"
                          v-decorator="[ 'bindingSpaceNumber', { rules: [{ required: true, message: '可绑定车位数!' }] }]"/>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          :disabled="isEdit"
          label="可绑定车牌数">
          <a-input-number :disabled="isEdit" :min="0" :max="2100000" :precision="0" placeholder="请输入可绑定车牌数" style="width:165px"
                          v-decorator="[ 'bindingCarNumber', { rules: [{ required: true, message: '可绑定车牌数!' }] }]"/>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="周期单位">
          <a-radio-group name="radioGroup" v-decorator="['cycleLength',  {initialValue:2}]">
            <a-radio :value=2>月</a-radio>
            <a-radio :value=1>天</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="周期收费金额(元)">
<!--          <a-input placeholder="每个周期单位对应收费金额"-->
<!--                   v-decorator="['charges',{ rules: [{ type: 'string', required: true, message: '请输入收费金额!' }] }]"/>-->
          <a-input-number placeholder="请输入周期收费金额" style="width:160px" :min="0" :max="9999999.99" :precision="2"  v-decorator="['charges',{ rules: [{ required: true, message: '请输入收费金额!' }] }]"
                    />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="满位处理方式">
          <a-select placeholder="请选择满位处理方式" :options="fullSpaceCarType" @select="fullSpaceCarTypeSelect"
                    v-decorator="['fullManageId', {initialValue:''}]"/>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          v-show="false"
          label="满位处理方式">
          <a-input placeholder="请输入满位处理方式车辆类型name(存放车辆类型名称 禁止入场为空)"
                   v-decorator="['fullManageName', {initialValue:'-1'}]"/>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          v-show="false"
          label="过期车辆类型">
          <a-input placeholder="请输入过期处理车辆类型名称" v-decorator="['overdueTypeName', {}]"/>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="过期车辆类型">
          <a-select :options="carTypeList" v-decorator="['overdueTypeId', {initialValue:''}]"
                    @select="overdueTypeSelect"></a-select>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="过期延期方式">
          <a-radio-group name="radioGroup" v-decorator="['overdueDelayWay',  {initialValue:1}]">
            <a-radio :value=1>顺延</a-radio>
            <a-radio :value=2>跳延</a-radio>
            <span style="margin-left: 80px">说明：跳延为允许选择新的月租开始日期。</span>
          </a-radio-group>
        </a-form-item>
        <!--存放编辑时是否修改了图片的标识-->
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          v-show="false"
          label="套餐展示图片url">
          <a-input placeholder="请输入套餐展示图片url" v-decorator="['imageUrl', {}]"/>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="套餐展示图片">
          <div class="clearfix">
            <a-upload
              :before-upload="beforeUpload"
              list-type="picture-card"
              :file-list="fileList"
              :remove="handleRemove"
              @preview="handlePreview"

            >
<!--              @change="handleChange"-->
              <div v-if="fileList.length<1">
              <a-icon type="plus" />
              <div class="ant-upload-text">
                Upload
              </div>
              </div>
            </a-upload>
            <!--            <a-modal :visible="previewVisible" :footer="null" @cancel="handleImgCancel">
                          <img alt="example" style="width: 100%" :src="previewImage" />
                        </a-modal>-->
            <a-modal class="imgModal" :visible="previewVisible" :footer="null" @cancel="handlePreviewCancel" style="color: #4d4d4d">
              <img alt="example" style="transform: rotate(0deg);width: 100%;" :src="previewImage" />
            </a-modal>
          </div>


        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          v-if="false"
          label="是否配置允许办理起始时间(1、是 2、否)">
          <a-input placeholder="请输入是否配置允许办理起始时间(1、是 2、否)" v-decorator="['allowHandleStarting', {}]"/>
        </a-form-item>
        <a-form-item
          v-if="false"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="是否配置允许办理截至时间(1、是 2、否)">
          <a-input placeholder="请输入是否配置允许办理截至时间(1、是 2、否)" v-decorator="['allowHandleOf', {}]"/>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="新办月租允许办理">
          <a-checkbox v-decorator="['allowHandleStarting', {valuePropName:'checked',initialValue:false}]"
                      style="margin-right: 14px">开始日期
          </a-checkbox>
          <a-checkbox v-decorator="['allowHandleOf', {valuePropName:'checked',initialValue:false}]"
                      style="margin-right: 14px">截止日期
          </a-checkbox>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="允许线上购买">
          <a-radio-group v-decorator="['allowOnlineBuy',  {initialValue:2}]" @change="allowOnlineBuyChange">
            <a-radio :value=2>不允许</a-radio>
            <a-radio :value=1>允许</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="允许线上续费">
          <a-radio-group v-decorator="['allowOnlineRenewal',  {initialValue:2}]">
            <a-radio :value=2>不允许</a-radio>
            <a-radio :value=1>允许</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="最大购买周期数">
<!--          v-show="showMaxCycle"-->
          <a-input-number placeholder="请输入最大购买周期数" style="width:165px" 
          v-decorator="[ 'maxCycle', {}]"
           :min="0" :max="2100000" :precision="0"/>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="套餐说明">
          <a-input placeholder="请输入套餐说明信息" v-decorator="['remark', {}]"/>
        </a-form-item>


      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import {httpAction, getAction, postAction} from '@/api/manage'
import pick from 'lodash.pick'
import moment from "moment"
import { getMonthlyParkInfoList } from '@api/api'
import Vue from "vue";
import {axios} from "@/utils/request";

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

export default {
  name: "MonthlyPackageInfoModal",
  data() {
    return {
      title: "操作",
      visible: false,
      model: {},
      labelCol: {
        xs: {span: 24},
        sm: {span: 5},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16},
      },

      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {
        parkCode: {rules: [{required: true, message: '请输入停车场编号!'}]},
      },
      carTypeList: [],
      fullSpaceCarType: [],
      url: {
        add: "/monthlyPackageInfo/add",
        edit: "/monthlyPackageInfo/edit",
        getCarTypeList: "/ConfigCarType/configCarType/parkCarTypeList",
        getParkMonthlyCarTypeList: "/ConfigCarType/configCarType/parkMonthlyCarTypeList",
        getParkInfos: "/parking/parkInfo/parkInfoList",
      },

      loading: false,
      file: {},
      isEdit: false,
      showMaxCycle: false,
      parkInfos: [],
      monthCarTypeList: [],
      fileList:[],
      previewVisible: false,
      previewImage: '',
    }
  },
  created() {
  },
  methods: {
    exeBase (file) {
      const that = this
      that.getBase64(file, (imageUrl) => {
        if (that.fileList.length < 1 ) {//判断图片数量及去重
          const file2 = file
          file2.url = imageUrl
          that.fileList = [...that.fileList, file]
          that.loading = false
        }
      })
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },

    allowOnlineBuyChange(e) {

      if (e.target.value === 2) {
        //不允许
        this.showMaxCycle = false
      }
      if (e.target.value === 1) {
        //允许
        this.showMaxCycle = true
        this.form.setFieldsValue({maxCycle: ''})
      }
    },
    handleChange({ fileList }) {
      this.fileList = fileList;
      this.beforeUpload(fileList[0])
      //当编辑弹框中该图片change事件发生时，在imageUrl中存储标识，标识用户是否重新选择了图片
      if (this.model.id) {
        this.form.setFieldsValue({imageUrl: "hasChangedImg"})
      }
    },
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isLt2M) {
        this.$message.error('图片大小不能超过10MB!');
        return false;
      }
      this.exeBase(file)
      return false;
    },
    getBase64 (file, callback) {
      return new Promise((resolve) => {
        let reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => {
          callback(reader.result)
          resolve('成功')
        }
      })
    },
    initCarTypeList() {

      var that = this
      let parkCode = this.form.getFieldValue("parkCode");
      postAction(this.url.getCarTypeList, {"parkCode": parkCode}).then((res) => {

        if (res.success) {
          that.carTypeList = [{label: "按车辆性质入场", value: "0"}]
          that.fullSpaceCarType = []
          res.result.forEach(carType => {
            that.carTypeList.push({
              label: carType.carTypeName,
              value: carType.id
            })
          })
          //满位处理方式

          let forbid = [{label: "禁止入场", value: "-1"}]
          that.fullSpaceCarType = forbid.concat(that.carTypeList)
          if (!that.isEdit) {
            if (that.carTypeList.length > 0) {
              that.form.setFieldsValue({overdueTypeId: that.carTypeList[0].value})
              that.form.setFieldsValue({overdueTypeName: that.carTypeList[0].label})
            }
            if (that.fullSpaceCarType.length > 0) {
              that.form.setFieldsValue({fullManageId: that.fullSpaceCarType[0].value})
              that.form.setFieldsValue({fullManageName: that.fullSpaceCarType[0].label})
            }
          }

        }
      })
    },
    parkInfoSelect(e, a) {
      let parkName = a.componentOptions.children[0].text
      this.form.setFieldsValue({parkName: parkName})
      this.form.setFieldsValue({monthlyTypeId: ''})
      this.form.setFieldsValue({fullManageId: ''})
      this.form.setFieldsValue({overdueTypeId: ''})
      this.initCarTypeList()
      this.initMonthCarTypeList()

    },
    monthlyTypeSelect(e, a) {
      let monthlyTypeName = a.componentOptions.children[0].text
      this.form.setFieldsValue({monthlyTypeName: monthlyTypeName})
    },
    fullSpaceCarTypeSelect(e, a) {
      let fullManageName = a.componentOptions.children[0].text
      this.form.setFieldsValue({fullManageName: fullManageName})
    },
    overdueTypeSelect(e, a) {
      let overdueTypeName = a.componentOptions.children[0].text
      this.form.setFieldsValue({overdueTypeName: overdueTypeName})
    },
    initMonthCarTypeList() {
      var that = this
      let parkCode = this.form.getFieldValue("parkCode");
      getAction(this.url.getParkMonthlyCarTypeList, {parkCode: parkCode}).then((res) => {
        if (res.success) {
          that.monthCarTypeList = []
          res.result.forEach(carType => {
            that.monthCarTypeList.push({
              label: carType.carTypeName,
              value: carType.id
            })
          })
          if (!that.isEdit) {
            if (that.monthCarTypeList.length > 0) {
              that.form.setFieldsValue({monthlyTypeId: that.monthCarTypeList[0].value})
              that.form.setFieldsValue({monthlyTypeName: that.monthCarTypeList[0].label})

            }
          }
        }
      })
    },
    handleRemove (file) {//删除图片
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
    },
    loadParkInfo() {
      const that = this
      getMonthlyParkInfoList().then((res) => {
        if (res.success) {
          if (res.result) {
            that.parkInfos = []
            res.result.forEach(parkInfo => {
              that.parkInfos.push({
                label: parkInfo.parkName,
                value: parkInfo.parkCode,
                key: parkInfo.parkCode
              })
            })
            if (!that.isEdit) {
              if (that.parkInfos.length > 0) {
                that.form.setFieldsValue({parkCode: that.parkInfos[0].value})
                that.form.setFieldsValue({parkName: that.parkInfos[0].label})
              }
            }
            that.initCarTypeList()
            that.initMonthCarTypeList()
          }
        }
      })
    },
    add() {
      this.edit({});
    },
    edit(record) {

      this.form.resetFields();
      this.loadParkInfo()

      this.model = Object.assign({}, record);
      this.visible = true;
      var that = this
      this.$nextTick(() => {

        that.fileList=[]
        if (JSON.stringify(record) !== '{}') {
          //编辑
          that.isEdit = true;
          that.fileList.push({
            uid: '-1',
            name: 'image.png',
            status: 'done',
            url:record.imageUrl
          })
          that.sourceFileList=that.fileList
        } else {
          //新增
          that.isEdit = false;
          that.showMaxCycle = false
        }that.form.setFieldsValue(pick(that.model, 'parkCode', 'parkName', 'monthlyTypeId', 'fullManageId', 'overdueTypeId', 'packageName', 'monthlyTypeName', 'fixedSpace', 'spaceFlag', 'bindingSpaceNumber', 'bindingCarNumber', 'cycleLength', 'fullManageName', 'overdueTypeName', 'overdueDelayWay', 'maxCycle', 'allowOnlineBuy', 'allowOnlineRenewal', 'parkingSlots', 'outsideBillingType', 'remark', 'edition', 'applicationStatus', 'imageUrl', 'createUserId', 'createUserName', 'updateUserId', 'updateUserName'))
        if (that.model.allowHandleStarting === 1) {
          that.form.setFieldsValue({allowHandleStarting: true})
        }
        if (that.model.allowHandleStarting === 2) {
          that.form.setFieldsValue({allowHandleStarting: false})
        }
        if (that.model.allowHandleOf === 1) {
          that.form.setFieldsValue({allowHandleOf: true})
        }
        if (that.model.allowHandleOf === 2) {
          that.form.setFieldsValue({allowHandleOf: false})
        }
        if (that.model.charges) {
          that.form.setFieldsValue({charges: parseFloat(that.model.charges / 100).toFixed(2)})
        }

        that.imageUrl = that.model.imageUrl

        //时间格式化
        that.form.setFieldsValue({workParkStartTime: that.model.workParkStartTime ? moment(that.model.workParkStartTime) : null})
        that.form.setFieldsValue({workParkEntTime: that.model.workParkEntTime ? moment(that.model.workParkEntTime) : null})
        that.form.setFieldsValue({weekendParkStartTime: that.model.weekendParkStartTime ? moment(that.model.weekendParkStartTime) : null})
        that.form.setFieldsValue({weekendParkEntTime: that.model.weekendParkEntTime ? moment(that.model.weekendParkEntTime) : null})
        that.form.setFieldsValue({holidaysParkStartTime: that.model.holidaysParkStartTime ? moment(that.model.holidaysParkStartTime) : null})
        that.form.setFieldsValue({holidaysParkEntTime: that.model.holidaysParkEntTime ? moment(that.model.holidaysParkEntTime) : null})
        that.form.setFieldsValue({takeTime: that.model.takeTime ? moment(that.model.takeTime) : null})
        that.form.setFieldsValue({updateTime: that.model.updateTime ? moment(that.model.updateTime) : null})


      });

    },
    close() {
      this.$emit('close');
      this.visible = false;
    },
    handleOk() {

      const that = this;
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true;
          let formData = Object.assign(this.model, values);
          let httpurl = '';
          let method = '';
          if (!this.model.id) {
            httpurl += this.url.add;
            method = 'post';
          } else {
            httpurl += this.url.edit;
            method = 'put';
            //判断用户时候重新选择了图片
            if(that.sourceFileList.length >0 && that.fileList.length>0){

              if(that.sourceFileList[0].url!==that.fileList[0].url){
                //用户修改了图片
                formData.imageUrl= "hasChangedImg"
              }
            }
            if(that.sourceFileList.length !== that.fileList.length ){

              formData.imageUrl= "hasChangedImg"

            }
          }
            formData.allowHandleStarting = formData.allowHandleStarting ? 1 : 2;
          formData.allowHandleOf = formData.allowHandleOf ? 1 : 2;
          //es6中将数字转化为字符串`${}`
          formData.charges = String(Number(formData.charges) * 100)
          let data = new FormData();
          that.fileList.forEach(file => {
            data.set("files[]", file);
          });
          this.$nextTick(() => {
            data.append("formData", JSON.stringify(formData))
            httpAction(httpurl, data,method).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.$emit('ok');
                that.fileList=[]
              } else {
                that.$message.warning(res.message);
              }
              that.confirmLoading = false;
            }).finally(() => {

              that.close();
            })
          })
        }
      })
    },
    handlePreviewCancel() {//点击关闭图片预览
      this.previewVisible = false;
    },
    handleCancel() {
      this.close()
    },

  }
}
</script>

<style lang="less" scoped>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

</style>
